<?php
/**
 * 用户相关接口
 * */

namespace App\Http\Controllers;

use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Model\SystemConfig;
use App\Http\Model\UserAccountCancel;
use App\Http\Model\UserLoginLog;
use App\Http\Services\ContentCheckServices;
use App\Http\Services\DeviceServices;
use App\Http\Services\FinanceServices;
use App\Http\Services\FriendsServices;
use App\Http\Services\MsgServices;
use App\Http\Services\PopularizeServices;
use App\Http\Services\RoomMsgServices;
use App\Http\Services\RoomServices;
use App\Http\Services\SystemConfigServices;
use App\Http\Services\SystemServices;
use App\Http\Services\TrendsServices;
use App\Http\Services\UserAnchorServices;
use App\Http\Services\UserFilterServices;
use App\Lib\SendSms;
use App\Lib\Publisher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Http\Services\UserServices;
use App\Http\Model\FormatCheck;
use App\Events\RoomRegisterEvent;
use App\Http\Services\MallServices;
use Illuminate\Support\Facades\Validator;
use App\Lib\Response;

class UserController extends BaseController
{
    protected $smsPrefix = 'sms_';
    protected $service;
    protected $thirdSourceConf = [1, 2, 3, 4, 5, 6, 7, 8, 9];//1:qq 2:微信 3：微博 4:华为 5.来来微信 7.天天微信 8.火火微信 9苹果登录
    protected $platformConf = [1, 2];//1:iOS 2:android
    protected $actConf = [1, 2];//1:绑定 2：解绑
    public static $expire = 7200;
    private $friends_services;
    private $room_services;
    private $service_msg;
    private $popularize_service;
    private $finance_services;
    private $service_room_msg;
    private $systemServices;
    private $contentCheckServices;
    private $deviceService;
    protected $mallService;//商品服务
    protected $trendsService;//动态服务
    protected $iniviteStartTime = '1730473200';//邀请活动开始时间 //2024/11/1 23:00:00
    protected $iniviteEndTime = '1740931199';//邀请活动结束时间 2025/3/2 23:59:59

    protected $modelSystemConfig;
    private $forbid_ip = 'FORBID:IP';

    public function __construct(UserServices $service, FriendsServices $friendsServices, RoomServices $roomServices, MsgServices $msgServices, PopularizeServices $popularizeServices, FinanceServices $financeServices, RoomMsgServices $roomMsgServices, DeviceServices $deviceServices)
    {
        $this->service = $service;
        $this->friends_services = $friendsServices;
        $this->room_services = $roomServices;
        $this->service_msg = $msgServices;
        $this->popularize_service = $popularizeServices;
        $this->finance_services = $financeServices;
        $this->service_room_msg = $roomMsgServices;
        $this->systemServices = new SystemServices();
        $this->contentCheckServices = new ContentCheckServices();
        $this->deviceService = $deviceServices;
        $this->mallService = new MallServices();//商品服务
        $this->trendsService = new TrendsServices();
        $this->modelSystemConfig = new SystemConfig();
    }

    /**
     * @desc 第三方登录
     * @date 2018/12/18
     * */
    public function third_login(Request $request)
    {

        $source = $request->post('source');
        $platform = $request->post('platform');
        $token = $request->post('token');
        $refreshToken = $request->post('refresh_token'); //微信必传
        $openId = $request->post('openid');
        $cancel = $request->post('cancel') ?? null;
        $deviceId = $request->post('deviceId') ?? '';
        $advertisingId = $request->post('advertisingId') ?? '';

        write_log('apiRequest', 'api_login_third_logs', $request->post());
        if (!$source || !in_array($source, $this->thirdSourceConf)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (!$platform || !in_array($platform, $this->platformConf)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (!$token) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        if ($source == 2 && !$refreshToken) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if ($source == 9 and empty($openId)) {// 苹果登录必传苹果用户唯一标识
            Response::returnResult(Hint::PARAM_ERROR);
        }
        //通过第三方接口注册
        $user_id = null;
        $thirdRet = $this->service->thirdLoginService($source, $platform, $token, $refreshToken, $openId, $cancel, $user_id);

        if ($thirdRet == Hint::USER_FORBID) {
            $forbidTime = $this->service->getForbidTime($user_id);
            $forbidInfo = $this->service->getBlockInfo($user_id);
            $forbidDurationTime = 0;
            if (!empty($forbidInfo)) {
                $forbidDurationTime = $forbidInfo['block_duration_time'];
            }
            Response::returnResult(Hint::USER_FORBID, ["forbid_time" => $forbidTime, "forbid_duration_time" => $forbidDurationTime]);
        }

        if ($thirdRet == Hint::USER_ACCOUNT_IS_CANCEL) {
            Response::returnResult(Hint::USER_ACCOUNT_IS_CANCEL);
        }

        if ($thirdRet === false) {
            Response::returnResult(Hint::THIRD_CHECK_ERROR);
        } else {
            $user_id = $thirdRet['user_id'] ?? null;
            if ($user_id !== null) {
                $this->service->user_login_log($user_id, $deviceId, $advertisingId);
            }
            $this->service->update_channel_guid($user_id);

            //进行版本号判断
            $bind_mobile = false;
            //新增是否需要手机用户资料 true 需要绑定 false 不需要
            if (empty($thirdRet) && $bind_mobile == false) {
                $userInfo = $this->service->get_current_user();
                if (empty($userInfo['mobile'])) {
                    //进行手机号绑定
                    $phone = $this->service->getFalseMobile();
                    $request->offsetSet('phone', $phone);
                    $request->offsetSet('sms_code', "000000");
                    //获取手机号
                    $this->thirdpart_bind_phone($request, true);
                }
            }

            $thirdRet['bind_mobile'] = $bind_mobile;

            Response::returnResult(Hint::SUCCESS, $thirdRet);
        }
    }

    /**
     * @desc 账号绑定页面初始化
     * @date 2019/1/2
     * */
    public function account_init(Request $request)
    {
        $this->service->checkToken();

        //通过第三方接口绑定解绑
        $initRet = $this->service->accountInitService();
        $gift_switch = $this->service->getGiftSwitch();
        if ($initRet === false) {
            Response::returnResult(Hint::ERROR);
        } else {
            $initRet['gift_status'] = $gift_switch;
            Response::returnResult(Hint::SUCCESS, $initRet);
        }
    }

    /**
     * @desc 第三方账号绑定/解绑
     * @date 2019/1/2
     * */
    public function third_move(Request $request)
    {
        $act_type = $request->post('act_type');
        $source = $request->post('source');
        $platform = $request->post('platform');
        $token = $request->post('token');
        $refreshToken = $request->post('refresh_token'); //微信必传
        $openId = $request->post('openid');
        if (!$act_type || !in_array($act_type, $this->actConf))
            Response::returnResult(Hint::PARAM_ERROR, []);

        if (!$source || !in_array($source, $this->thirdSourceConf))
            Response::returnResult(Hint::PARAM_ERROR, []);

        if (!$platform || !in_array($platform, $this->platformConf))
            Response::returnResult(Hint::PARAM_ERROR, []);

        //解绑token refresh_token 非必需
        if ($act_type == 1) {
            if (!$token)
                Response::returnResult(Hint::PARAM_ERROR, []);
            if ($source == 2 && !$refreshToken)
                Response::returnResult(Hint::PARAM_ERROR, []);
            if (!$openId)
                Response::returnResult(Hint::PARAM_ERROR, []);
        }

        $this->service->checkToken();

        //通过第三方接口绑定解绑
        $thirdRet = $this->service->thirdPartBindService($act_type, $source, $platform, $token, $refreshToken, $openId);
        //解绑判断是否已经绑定手机号
        if ($thirdRet === Hint::USER_ACCOUNT_MOBILE_NOT_BIND) {
            Response::returnResult(Hint::USER_ACCOUNT_MOBILE_NOT_BIND, []);
        }
        if ($thirdRet === false) {
            Response::returnResult(Hint::THIRD_CHECK_ERROR, []);
        } else {
            Response::returnResult(Hint::SUCCESS, []);
        }
    }

    /**
     * @desc 退出登录
     * @date 2018/12/21
     * */
    public function login_out()
    {
        $this->service->login_out();
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * @desc 获取手机号验证码 interface
     * @date 2018/12/18
     * */
    public function sms_code(Request $request)
    {
        $userAgent = $request->userAgent();
        $phone = trim($request->input('phone'));
        $sms_type = $request->input('sms_type');
        $deviceId = $request->input('deviceId', '');
        $smsToken = $request->input('sms_token', '');
        $isCheckMobile = false;
        //版本低的安卓特殊处理
        if (!empty($userAgent)) {
            $userAgent = explode(';', $userAgent);
            $androidVersion = ($userAgent[1] == 'Android') ? $userAgent[2] : $userAgent[1];
            $isAndroid = ($userAgent[1] == 'Android') ? $userAgent[1] : $userAgent[2];
            if ($androidVersion < '1.2.2' && $isAndroid == 'Android') {
                // Response::returnResult(Hint::ERR_NORMAL, [], 'code:260 版本过低,请更新APP版本');
            }
        }

        if (empty($phone)) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR, [], 'code:265 手机号不可为空');
        }
        if (strlen($phone) != 11) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR, [], 'code:268 手机号格式存在错误');
        }

        $alicodeConfig = $this->systemServices->getAliVerify();
        if ($alicodeConfig['status'] == 1) {
            if (empty($smsToken)) {
                Response::returnResult(Hint::ERR_NORMAL, [], 'code:274 系统检测您的版本过低,请升级最新版本');
            }
            $cacheSms = Redis::get('ALI:VERIFY:TOKEN:' . $phone);
            if (($cacheSms != md5($phone)) || empty($cacheSms)) {
                Response::returnResult(Hint::ERR_NORMAL, [], 'code:278 验证失效');
            }
        }

        // if (!FormatCheck::checkPhone($phone, $isCheckMobile)) {
        // Response::returnResult(Hint::PHONE_FORMAT_ERR, [], '手机号格式存在错误');
        // }
        if (strlen($sms_type) == 0) {
            Response::returnResult(Hint::PARAM_ERROR, [], 'code:286 缺少参数');
        }

        if (checkAppEnv()) {
            $redisKey = $this->smsPrefix . $phone;
            $this->redisCache($redisKey, '123456', 300);
            Response::returnResult(Hint::SUCCESS);
        }

        //每日次数限制
        if (!redis_num_lock('CACHE:MAX:SEND:CODE:' . date("Ymd") . ':' . $phone, 86400, 5)) {
            Response::returnResult(Hint::NOT_ALLOW_SEND_CODE, [], 'code:291 验证码每日限制最多5次');
        }

        if (!redis_lock('SMS' . $phone, 60)) {
            Response::returnResult(Hint::NOT_ALLOW_SEND_CODE, [], 'code:295 获取验证码频繁');
        }

        if (empty($deviceId)) {
            write_log('smsCode', 'smsCode deviceId为空', ['request' => $request->all()]);
        }

        //发送短信
        $expireTime = 5 * 60;
        $smsCode = randomkeys();
        $smsObj = new SendSms();
        $result = $smsObj->spSendSingleSms($phone, $smsCode);

        if ($result) {
            //redis 存储
            $redisKey = $this->smsPrefix . $phone;
            $this->redisCache($redisKey, $smsCode, $expireTime);
            Response::returnResult(Hint::SUCCESS);
        } else {
            Response::returnResult(Hint::ERROR, [], 'code:348 请求失败');
        }
    }

    /**
     * @desc 手机号注册 interface[不执行删除验证码]
     * @date 2018/12/18
     * */
    public function phone_register(Request $request, $smsRegister = false)
    {
        $phone = $request->input('phone');
        $sms_code = $request->input('sms_code');
        $inviteCode = $request->input('invite_code');
        $password = $request->input('password');
        $deviceId = $request->input('deviceId', '');

        write_log('user-invite', 'phone_register', ['invite_code' => $inviteCode, 'phone' => $phone]);

        //add by zxiaofee 手机注册 判断是否在禁止手机列表里
        if (UserFilterServices::inForbidRegisterPhoneList($phone)) {
            Response::returnResult(Hint::ERR_SYS_FAIL, null, '手机号异常，禁止注册');
        }

        if (!$phone || !FormatCheck::checkPhone($phone)) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR);
        }
        if (!$sms_code || !$password) { //增加密码
            Response::returnResult(Hint::PARAM_ERROR);
        }

        //6-16密码
        if (!FormatCheck::checkPassword($password)) {
            Response::returnResult(Hint::PASSWORD_NOT_ACCORD);
        }

        // 万能短信验证码
        $universalCode = $this->modelSystemConfig->getUniversalCodeConfig();
        if ($sms_code != $universalCode) {
            $sms_cache_code = $this->redisCacheGet($this->smsPrefix . $phone);
            if ($sms_cache_code != $sms_code) {
                Response::returnResult(Hint::SMS_CODE_ERROR);
            }
        }

        //验证
        if (!$this->service->checkUserService($phone)) {
            Response::returnResult(Hint::USER_IS_EXIST);
        } else {
            try {
                $inviteUid = 0;
                $inviteUserId = 0;
                $inviteUserIdNew = 0;

                $inviteUserData = $this->service->getUserInfoByCode($inviteCode);
                if (!empty($inviteUserData) && $inviteUserData['is_open_code'] == 1) {
                    $inviteUserIdNew = $inviteUserData['user_id'];
                }

                // todo 注册
                $userId = $this->service->createUserService($phone, $password, $inviteUid, 0, '', '', $inviteUserIdNew);
                if ($userId) {
                    $this->service->createWalletService($userId);
                    //发送动态
                    $this->trendsService->registerTrend($userId);
                    //查询数据
                    $data = $this->service->getResponseData($userId);
                    event(new RoomRegisterEvent($data, 1));
                    // 绑定推荐人
                    $this->popularize_service->check_recommend_code($userId);

                    // 写注册日志、广告归因上报
                    $this->service->user_register_log($userId);

                    $this->service->get_user_register_log($userId);
                    $this->service->update_channel_guid($userId);

                    // 判断邀请用户UID >0 则增加邀请用户参数user_id
                    if ($inviteUid > 0) {
                        $data['invite_user_id'] = $inviteUserId;
                    } else {
                        $data['rong_token'] = $this->service->get_rong_token($data);
                        $data['user_token'] = $this->service->getUserToken();
                    }

                    $this->redisCacheDel($this->smsPrefix . $phone);
                    // TODO 发布消息通知
                    $content = [
                        'user_id' => $userId,
                        'target_id' => $inviteUserId,
                        'time' => time(),
                        'deviceid' => $deviceId,
                        'timestamp' => msectime(),
                        'ip' => client_ip(),
                        'is_phone_exiist' => 0,
                        'country_code' => '0086',
                        'ua' => $this->service->parse_app_UA()
                    ];

                    $this->systemServices->deviceRiskQueue($content);
                    if ($smsRegister) {
                        Response::returnResult(Hint::PHONE_STATUS_1, $data);
                    }
                    Response::returnResult(Hint::SUCCESS, $data);
                } else {
                    Response::returnResult(Hint::ERROR, []);
                }
            } catch (\Exception $e) {
                Log::debug("手机号注册-捕获异常：" . $e->getMessage());
                Response::returnResult(Hint::ERR_SYS_FAIL, ['error_msg' => $e->getMessage()]);
            }
        }
    }

    /**
     * @desc 验证验证码 interface[保留验证码]
     * @date 2018/12/18
     * */
    public function check_sms_code(Request $request)
    {
        $phone = $request->input('phone');
        $sms_code = $request->input('sms_code');

        if (!$phone || !FormatCheck::checkPhone($phone)) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR);
        }
        if (!$sms_code) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        //校验验证码
        $sms_cache_code = $this->redisCacheGet($this->smsPrefix . $phone);
        if (empty($sms_cache_code) || ($sms_cache_code != $sms_code)) {
            Response::returnResult(Hint::SMS_CODE_ERROR);
        }
        Response::returnResult(Hint::SUCCESS);

    }

    /**
     * @desc 设置密码
     * @date 2018/12/18
     * */
    public function set_password(Request $request)
    {
        $phone = $request->input('phone');
        $password = $request->input('password');
        $sms_code = $request->input('sms_code');
        $type = (int) $request->input('type'); //1:修改/设置密码 （需登录态）（默认为1）2：忘记密码找回密码
        $type = !empty($type) ? $type : 1;

        if (!$password || !FormatCheck::validPassword($password)) {
            Response::returnResult(Hint::PASSWORD_FORMAT_ERR);
        }

        if (!$phone || !FormatCheck::checkPhone($phone)) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR);
        }

        if ($type == 1) {
            $this->service->checkToken();
            if ($this->service->phoneStatus($phone) != 2) {
                Response::returnResult(Hint::PHONE_NOT_NOW_USER);
            }
        } else {
            if ($this->service->phoneStatus($phone) == 1) {
                Response::returnResult(Hint::USER_IS_NOT_EXIST);
            }
        }

        if (!$password) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (!$sms_code) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        if ($this->checkSmsCode($phone, $sms_code)) {
            $result = $this->service->setUserPassword($phone, $password);
            if ($result || $result !== false) {
                $this->redisCacheDel($this->smsPrefix . $phone);
                Response::returnResult(Hint::SUCCESS);
            } else {
                Response::returnResult(Hint::ERROR);
            }
        } else {
            Response::returnResult(Hint::SMS_CODE_ERROR);
        }
    }

    /**
     * @desc 手机号密码登录 interface
     * @date 2018/12/18
     * */
    public function login_with_password(Request $request)
    {
        $phone = trim($request->input('phone'));//手机号
        $password = $request->input('password');//密码
        $cancel = $request->input('cancel') ?? null;//是否取消账号申请 0=取消注销
        $deviceId = $request->input('deviceId') ?? '';//鉴定风险账号要用到
        $advertisingId = $request->input('advertisingId') ?? '';//广告标识符
        if (empty($phone)) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR, [], 'code:552 手机号不可为空');
        }
        if (strlen($phone) != 11) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR, [], 'code:555 手机号格式存在错误');
        }
        // if (!$phone || !FormatCheck::checkPhone($phone)) {
        //     Response::returnResult(Hint::PHONE_FORMAT_ERR);
        // }
        if (UserServices::isLockedByLoginPasswordErr($phone)) {
            Response::returnResult(Hint::USER_LOGIN_FAILED_TOO_MANY, [], 'code:561 登录失败次数过多，请10分钟后再试');
        }

        if (!$password) {
            Response::returnResult(Hint::PARAM_ERROR, [], 'code:565 请输入密码');
        }

        //type=1：手机号密码 2：手机号验证码 3：第三方
        $user_id = null;
        $ret = $this->service->local_login(1, ['phone' => $phone, 'password' => $password], $user_id, $cancel);
        //获取设备是否封禁状态
        if ($ret == Hint::DEVICE_FORBID) {
            Response::returnResult(Hint::DEVICE_FORBID, [], 'code:573 设备已封禁');
        }

        if ($ret == Hint::USER_IS_NOT_EXIST) {
            Response::returnResult(Hint::USER_IS_NOT_EXIST, [], 'code:577 用户不存在');
        }

        if ($ret == Hint::USER_FORBID) {//账号被封号
            $forbidTime = $this->service->getForbidTime($user_id);
            $forbidInfo = $this->service->getBlockInfo($user_id);
            $forbidDurationTime = 0;
            if (!empty($forbidInfo)) {
                $forbidDurationTime = $forbidInfo['block_duration_time'];
            }

            Response::returnResult(Hint::USER_FORBID, ["forbid_time" => $forbidTime, "forbid_duration_time" => $forbidDurationTime]);
        }

        if ($ret == Hint::USER_ACCOUNT_IS_CANCEL) {//用户申请了注销账号
            Response::returnResult(Hint::USER_ACCOUNT_IS_CANCEL, [], 'code:592 该用户已申请账号注销');
        }

        if ($ret == Hint::ERROR) {//报错
            Response::returnResult(Hint::ERROR, [], 'code:596 登录失败');
        }

        if ($ret == Hint::PASSWORD_ERROR) {//密码错误
            UserServices::addLoginPasswordErrNum($phone);
            Response::returnResult(Hint::PASSWORD_ERROR, [], 'code:601 密码错误');
        }

        #region  检查IP是否封禁
        $ip = client_ip();
        // $ipSegments = explode('.', $ip);
        // $ipPrefix = implode('.', array_slice($ipSegments, 0, 3));
        // write_log('zq', 'forbid_ip', ['ip' => $ipPrefix]);
        $forbidIps = Redis::SISMEMBER($this->forbid_ip, $ip);
        $ips = Redis::SMEMBERS($this->forbid_ip);
        if ($forbidIps) {
            write_log('zq', 'forbid_ip', ['forbidIps' => $forbidIps,
            //  'ipSegments' => $ipSegments, 'ipPrefix' => $ipPrefix, 
            'ip' => $ip, 'ips' => $ips]);
            Response::returnResult(Hint::DEVICE_FORBID, [], 'IP已封禁');
        }
        #endregion


        $this->service->user_login_log($user_id, $deviceId, $advertisingId);
        $this->service->update_channel_guid($user_id);
        Response::returnResult(Hint::SUCCESS, $ret);
    }

    /**
     * APP 手机号验证码登录
     * @param Request $request
     */
    public function appLoginSmsCode(Request $request)
    {
        $phone = $request->input('phone') ?? '';
        $smsCode = $request->input('sms_code') ?? '';
        $cancel = $request->input('cancel') ?? null;
        $cancel = 0;
        $deviceId = $request->input('deviceId') ?? '';
        $advertisingId = $request->input('advertisingId') ?? '';

        if (!$phone || !FormatCheck::checkPhone($phone)) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR);
        }

        if (UserServices::isLockedByLoginPasswordErr($phone)) {
            Response::returnResult(Hint::USER_LOGIN_FAILED_TOO_MANY);
        }

        if (!$smsCode) {
            Response::returnResult(Hint::SMS_CODE_ERROR);
        }

        // 万能短信验证码
        $universalCode = $this->modelSystemConfig->getUniversalCodeConfig();
        if ($smsCode != $universalCode) {
            $checkSmsCode = $this->redisCacheGet($this->smsPrefix . $phone);
            if (empty($checkSmsCode) || ($checkSmsCode != $smsCode)) {
                UserServices::addLoginPasswordErrNum($phone);
                Response::returnResult(Hint::SMS_CODE_ERROR);
            }
        }

        //如果当前用户为空
        if (!empty($this->service->currentUserId)) {
            // 检测手机号是否存在
            $getUserInfoByPhone = $this->service->getUserInfoByPhone($phone);
            if (empty($getUserInfoByPhone)) {
                $getUserData = $this->service->getUserData($this->service->currentUserId, true);
                // 校验不是正确的手机号并且不等于当前验证的手机号
                if (!empty($getUserData['phone']) and !FormatCheck::checkPhone($getUserData['phone']) and $getUserData['phone'] != $phone) {
                    // 更新游客用户手机号
                    $modifyVisitorPhone = $this->service->modifyVisitorPhone($this->service->currentUserId, $phone);
                    //写注册日志、广告归因上报
                    $this->service->user_register_log($this->service->currentUserId);
                    //记录游客绑定手机号日志
                    if (!$modifyVisitorPhone) {
                        write_log('visitorLogin', '更新游客用户手机号失败:user_id:', $this->service->currentUserId);
                        Response::returnResult(Hint::ERROR);
                    }
                }
            }
        }

        //获取手机号注册状态
        $phoneStatus = $this->service->phoneStatus($phone);
        //进行账号注册 status = 1
        if ($phoneStatus == 1) {
            $request->offsetSet('password', $smsCode);
            $this->phone_register($request, true);
            return;
        }

        //进行账号登录 //type=1：手机号密码 2：手机号验证码 3：第三方
        $ret = $this->service->local_login(2, ['phone' => $phone], $user_id, $cancel);
        //获取设备是否封禁状态
        if ($ret == Hint::DEVICE_FORBID) {
            Response::returnResult(Hint::DEVICE_FORBID, [], '设备已封禁');
        }

        #region  检查IP是否封禁
        $ip = client_ip();
        // $ipSegments = explode('.', $ip);
        // $ipPrefix = implode('.', array_slice($ipSegments, 0, 3));
        // write_log('zq', 'forbid_ip', ['ip' => $ipPrefix]);
        $forbidIps = Redis::SISMEMBER($this->forbid_ip, $ip);
        $ips = Redis::SMEMBERS($this->forbid_ip);
        if ($forbidIps) {
            write_log('zq', 'forbid_ip', ['forbidIps' => $forbidIps,
            //  'ipSegments' => $ipSegments, 'ipPrefix' => $ipPrefix, 
             'ip' => $ip, 'ips' => $ips]);
            Response::returnResult(Hint::DEVICE_FORBID, [], 'IP已封禁');
        }
        #endregion


        if ($ret == Hint::USER_IS_NOT_EXIST) {
            Response::returnResult(Hint::USER_IS_NOT_EXIST);
        }
        if ($ret == Hint::USER_FORBID) {
            $forbidTime = $this->service->getForbidTime($user_id);
            $forbidInfo = $this->service->getBlockInfo($user_id);
            $forbidDurationTime = 0;
            if (!empty($forbidInfo)) {
                $forbidDurationTime = $forbidInfo['block_duration_time'];
            }
            Response::returnResult(Hint::USER_FORBID, ["forbid_time" => $forbidTime, "forbid_duration_time" => $forbidDurationTime]);
        }
        if ($ret == Hint::USER_ACCOUNT_IS_CANCEL) {
            Response::returnResult(Hint::USER_ACCOUNT_IS_CANCEL, [], 'code:707 该用户已申请账号注销');
        }
        if ($ret == Hint::ERROR) {
            Response::returnResult(Hint::ERROR, [], 'code:710 登录失败,请重试');
        }
        if ($ret == Hint::PASSWORD_ERROR) {
            Response::returnResult(Hint::PASSWORD_ERROR, [], 'code:713 登录密码错误');
        }

        $this->service->user_login_log($user_id, $deviceId, $advertisingId);
        $this->service->update_channel_guid($user_id);
        Response::returnResult(Hint::SUCCESS, $ret);
    }

    /**
     * @desc 编辑用户资料
     * @param $nick_name required true
     * @param $user_uid
     * @date 2018/12/18
     * */
    public function user_edit(Request $request)
    {
        $home = $request->post("home");
        $nickname = $request->post("nickname");
        $gender = $request->post("gender");
        $birthday = $request->post("birthday");
        $images = $request->post("images");
        $affective_state = $request->post("affective_state");
        $occupation = $request->post("occupation");
        $school = $request->post("school");
        $sign = $request->post("sign");
        $voice = $request->post("voice");
        $voice_time = $request->post("voice_time");
        $vest_switch = $request->post("vest_switch") ?? -1;
        $height = $request->post('height', 0);
        $mood_id = (int) $request->post("mood_id");
        $identity_role = (int) $request->post("identity_role");
        $chat_sign = $request->post('chat_sign');
        $prepare_img = $request->post('prepare_img');//预设头像
        $user = $this->service->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::LOGIN_OUT);
        }

        //国庆期间不允许修改昵称和头像
        list($forbiddenStart, $forbiddenEnd) = SystemConfigServices::getForbiddenTimeForUpdate();
        if (time() >= $forbiddenStart && time() < $forbiddenEnd) {
            $create_time = isset($user['create_timestamp']) ? $user['create_timestamp'] : time();
            if ((time() - $create_time) > 30 * 60) {
                Response::returnResult(Hint::NATIONAL_FORBID_UPDATE, ['error_msg' => '暂时无法修改~']);
            }
        }

        if ($nickname != null) {
            if (!$this->service->nickCheck($nickname))
                Response::returnResult(Hint::NICKNAME_EXIST, ['error_msg' => Hint::getErrCodeMsg(Hint::NICKNAME_EXIST)]);
        }

        $inviteCode = $request->post('invite_code', '');// 邀请码（所属邀请人）
        write_log('user-invite', 'user_edit', ['invite_code' => $inviteCode]);
        $inviteUserId = 0;
        $inviteUserIdNew = 0;// 邀请人uid

        if (!empty($inviteCode)) {
            $inviteUserData = $this->service->getUserInfoByCode($inviteCode);
            if (!empty($inviteUserData) && $inviteUserData['is_open_code'] == 1) {
                $inviteUserIdNew = $inviteUserData['user_id'];
            }
        }

        //         todo 检测邀请码是否存在（将code转成user_id值）
//         if (!empty($inviteCode)) {
//             $inviteUserData = $this->service->getUserInfoByCode($inviteCode);
//             if (empty($inviteUserData)) {
//                 Response::returnResult(Hint::USER_INVITE_CODE_NO_EXIST, ['error_msg' => '邀请码用户不存在']);
//             }
//             $inviteUserId = $inviteUserData['user_id'];
//
//             //活动期间要校验
//             if(time()>=$this->iniviteStartTime && time()<=$this->iniviteEndTime) {
//                 //设备是否存在
//                 $check = $this->service->checkGuidHas($user['user_id'], $user['guid']);
//                 if(!$check) {
//                     $inviteUserId = 0;
//                 }
//             }else{
//                 $inviteUserId = 0;
//             }
//         }

        //添加内容检测
        $checkResult = $this->checkUserContent($request, $nickname, $sign, $voice, $images, $prepare_img);
        if (isset($checkResult['code']) && $checkResult['code'] == Hint::ERR_NORMAL) {
            Response::returnResult(Hint::ERR_NORMAL, [], $checkResult['msg']);
        }
        $result = $this->service->editUserData(
            $home,
            $nickname,
            $gender,
            $birthday,
            $images,
            $affective_state,
            $occupation,
            $school,
            $sign,
            $voice,
            $voice_time,
            $inviteUserId,
            $vest_switch,
            $height,
            $mood_id,
            $identity_role,
            $chat_sign,
            $inviteUserIdNew
        );
        //注释掉，上传头像审核的情况下不写入user信息，相当于没有修改，会直接拦截
        /*if($result == false){
            Response::returnResult(Hint::NOT_ALLOWED, ['error_msg' => Hint::getErrCodeMsg(Hint::NOT_ALLOWED)]);
        }*/

        Response::returnResult(Hint::SUCCESS);
    }

    public function edit_user(Request $request)
    {
        $user_id = $request->post("user_id", 0);
        $images = $request->post("images", '');
        $nickname = $request->post('nickname', '');
        $gender = $request->post('gender', '');

        $result = $this->service->setEditUser($user_id, $nickname, $images, $gender);
        if ($result !== false) {
            Response::returnResult(Hint::SUCCESS);
        } else {
            Response::returnResult(Hint::ERROR);
        }
    }

    public function edit_base_info(Request $request)
    {
        $user_id = $request->post("user_id", 0);
        $nickname = $request->post('nickname', '');
        $gender = $request->post('gender', 0);
        $birthday = $request->post('birthday', 0);
        $images = $request->post("images", '');

        $result = $this->service->setUserBaseInfo($user_id, $nickname, $gender, $birthday, $images);
        if ($result !== false) {
            Response::returnResult(Hint::SUCCESS);
        } else {
            Response::returnResult(Hint::ERROR);
        }
    }

    /**
     * @desc 绑定/更换手机号
     * @date 2018/12/18
     * */
    public function bind_phone(Request $request)
    {
        $this->service->checkToken();
        if (!$request->post('phone') || !$request->post('sms_code') || !FormatCheck::checkPhone($request->post('phone')))
            Response::returnResult(Hint::PARAM_ERROR, []);
        //自增id
        if (!$this->checkSmsCode($request->post('phone'), $request->post('sms_code')))
            Response::returnResult(Hint::SMS_CODE_ERROR, []);

        //绑定手机号
        if (!$this->service->checkUserService($request->post('phone')))
            Response::returnResult(Hint::PHONE_IS_EXIST, []);

        $bindRes = $this->service->bindPhoneService($request->post('phone'));
        if ($bindRes !== false) {
            $this->redisCacheDel($this->smsPrefix . $request->post('phone'));
            Response::returnResult(Hint::SUCCESS, []);
        } else {
            Response::returnResult(Hint::ERROR, []);
        }
    }

    /**
     * @desc 第三方登录新用户绑定手机号
     * @date 2018/12/18
     * */
    public function thirdpart_bind_phone(Request $request, $skipSms = false)
    {
        $phone = $request->post('phone');
        $sms_code = $request->post('sms_code');
        $source = $request->post('source');
        $openid = $request->post('openid');
        $deviceId = $request->post('deviceId');
        $inviteCode = $request->post('invite_code', '');// 邀请码（所属邀请人）


        if ($skipSms == false && (!$phone || !$sms_code || !FormatCheck::checkPhone($phone)))
            Response::returnResult(Hint::PARAM_ERROR, []);

        if (!$source || !in_array($source, $this->thirdSourceConf) || !$openid)
            Response::returnResult(Hint::PARAM_ERROR, []);

        if (!$this->checkSmsCode($request->post('phone'), $request->post('sms_code')) && $skipSms == false)
            Response::returnResult(Hint::SMS_CODE_ERROR, []);

        // 邀请用户ID
        $inviteUserId = 0;

        // todo 检测邀请码是否存在（将code转成user_id值）
        if (!empty($inviteCode)) {
            $inviteUserData = $this->service->getUserInfoByCode($inviteCode);
            if (empty($inviteUserData)) {
                Response::returnResult(Hint::USER_INVITE_CODE_NO_EXIST, ['error_msg' => '邀请码用户不存在']);
            }
            if (empty($inviteUserData['is_open_code'])) {
                Response::returnResult(Hint::USER_INVITE_CODE_NO_EXIST, ['error_msg' => '邀请码不可用']);
            }

            $inviteUserId = $inviteUserData['user_id'];
        }


        $bindRet = $this->service->thirdUserBind($phone, $openid, $source, $inviteUserId);
        if ($bindRet !== false) {
            $this->redisCacheDel($this->smsPrefix . $request->post('phone'));

            // 绑定推荐人
            $this->popularize_service->check_recommend_code($bindRet['user_id']);

            // 写注册日志、广告归因上报
            $this->service->user_register_log($bindRet['user_id']);

            $this->service->update_channel_guid($bindRet['user_id']);
            // TODO 发布消息通知
            $content = [
                'user_id' => $bindRet['user_id'],
                'time' => time(),
                'deviceid' => $deviceId,
                'timestamp' => msectime(),
                'ip' => client_ip(),
                'is_phone_exiist' => 0,
                'country_code' => '0086',
                'ua' => $this->service->parse_app_UA()
            ];
            $this->systemServices->deviceRiskQueue($content);
            Response::returnResult(Hint::SUCCESS, $bindRet);
        } else {
            Response::returnResult(Hint::ERROR, []);
        }

    }

    /**
     * @desc 获取用户信息
     * @date 2018/12/18
     * */
    public function get_user_info(Request $request)
    {
        $this->service->checkToken();

        if (!$request->get('user_id')) {
            Response::returnResult(Hint::SUCCESS);
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $user_id = (int) $request->get('user_id');
        $cur_user = $this->service->get_current_user();
        $self = $cur_user['user_id'] == $user_id;
        $result = $this->service->getResponseData($user_id, $self);
        if (!empty($result)) {
            Response::returnResult(Hint::SUCCESS, $result);
        } else {
            Response::returnResult(Hint::SUCCESS);
            Response::returnResult(Hint::ERROR);
        }
    }

    /**
     * 房间里获取用户信息
     * @param Request $request
     */
    public function get_in_room_user_info(Request $request)
    {
        $this->service->checkToken();

        if (!$request->get('user_id')) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $user_id = (int) $request->get('user_id');
        $room_id = (int) $request->get('room_id');
        $union_id = (int) $request->get('union_id') ?? 0;
        $loginUserId = $this->getLoginUserId();
        $result = $this->service->getInRoomUserInfo($room_id, $user_id, false, $union_id, $loginUserId);
        if (empty($result)) {
            Response::returnResult(Hint::ERROR);
        }
        Response::returnResult(Hint::SUCCESS, $result);
    }

    /**
     * @desc 获取用户详细信息
     * @date 2018/12/19
     * */
    public function get_user_info_detail(Request $request)
    {
        $this->service->checkToken();

        if (!$request->get('user_id')) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $user_id = (int) $request->get('user_id');
        $cur_user_id = null;
        $result = $this->service->getDetailResponseData($user_id, $cur_user_id);

        if (!empty($result)) {
            if (!empty($cur_user_id)) {
                // 屏蔽阅读个人的消息
                //$this->service_msg->personal_read($user_id, $cur_user_id);
            }
            Response::returnResult(Hint::SUCCESS, $result);
        } else {
            Response::returnResult(Hint::ERROR);
        }
    }


    /**
     * @desc 密码校验/用于换绑手机
     * @param string $phone 非必传
     * @param string $password
     * @date 2018/12/21
     * */
    public function check_password(Request $request)
    {
        $this->service->checkToken();
        $phone = $request->post('phone');
        $password = $request->post('password');

        if ($phone) {
            if (!FormatCheck::checkPhone($phone))
                Response::returnResult(Hint::PHONE_FORMAT_ERR, []);
        }

        if (!$password)
            Response::returnResult(Hint::PARAM_ERROR, []);

        $result = $this->service->passwordCheck($phone, $password);
        if ($result) {
            Response::returnResult(Hint::SUCCESS, []);
        } else {
            Response::returnResult(Hint::PASSWORD_ERROR, []);
        }
    }

    /**
     * @desc 修改密码[通过旧密码修改]
     * @param string $old_password
     * @param string $new_password
     * */
    public function set_password_by_password(Request $request)
    {
        $old_password = $request->input('old_password');
        $new_password = $request->input('new_password');
        if (!$old_password || !$new_password)
            Response::returnResult(Hint::PARAM_ERROR);

        if (!FormatCheck::checkPassword($new_password)) {
            Response::returnResult(Hint::PASSWORD_NOT_ACCORD);
        }
        $check_ret = $this->service->passwordCheck('', $old_password);
        if (!$check_ret)
            Response::returnResult(Hint::PASSWORD_ERROR);

        $ret = $this->service->setUserPasswordWToken($new_password);
        if ($ret === false) {
            Response::returnResult(Hint::ERROR);
        }
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * @desc 手机校验/是否已平台注册
     * @date 2018/12/21
     * */
    public function check_plat_phone(Request $request)
    {

        $phone = trim($request->get('phone'));
        if (empty($phone)) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR, []);
        }
        if (!FormatCheck::checkPhone($phone)) {
            Response::returnResult(Hint::PHONE_FORMAT_ERR, []);
        }
        $status = $this->service->phoneStatus($phone);
        if ($status == 1) {
            Response::returnResult(Hint::PHONE_STATUS_1, []);
        } elseif ($status == 2) {
            Response::returnResult(Hint::PHONE_STATUS_2, []);
        } elseif ($status == 3) {
            Response::returnResult(Hint::PHONE_STATUS_3, []);
        } else {
            Response::returnResult(Hint::PHONE_STATUS_4, []);
        }
    }

    /**
     * 屏蔽用户
     * @param Request $request
     */
    public function set_forbid_user(Request $request)
    {
        $this->service->set_cross();
        $user_id = (int) $request->post('user_id');
        $timeout = (int) $request->post('timeout');
        $is_limit_ip = (int) $request->post('is_limit_ip') ?? 0;
        if ($user_id <= 0) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $room_id = null;
        $this->service->set_forbid_user($user_id, $timeout, $room_id);
        if (!empty($room_id)) {
            // 当前 User 踢出房间
            $this->service_room_msg->command_user_out($room_id, $user_id, 0);
            // 通知 房间内其它用户，User离开房间
            $this->service_room_msg->broadcast_user_out($room_id, $user_id);
        }
        if (!empty($is_limit_ip)) {
            $this->service->set_forbid_ip($user_id);
        }

        write_log(
            'UserSet' . (isCli() ? '-cli' : ''),
            '[INFO] 屏蔽用户',
            ['uid' => $user_id, 'is_ip' => $is_limit_ip, 'rid' => $room_id]
        );
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 解封用户
     * @param Request $request
     */
    public function remove_forbid_user(Request $request)
    {
        $this->service->set_cross();
        $user_id = (int) $request->post('user_id');
        if ($user_id <= 0) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $this->service->remove_forbid_user($user_id);
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 屏蔽列表
     * @param Request $request
     */
    public function get_forbid_list(Request $request)
    {
        $list = $this->service->get_forbid_list();
        Response::returnResult(Hint::SUCCESS, $list);
    }

    //校验验证码
    private function checkSmsCode($phone, $sms_code)
    {
        $cache_sms_code = $this->redisCacheGet($this->smsPrefix . $phone);
        if ($sms_code == $cache_sms_code) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 搜索用户
     * @param Request $request
     */
    public function search(Request $request)
    {
        $word = $request->get('word');
        if ($word == null) {
            Response::returnResult(Hint::PARAM_ERROR, []);
        }
        $data = $this->service->search($word);
        Response::returnResult(Hint::SUCCESS, $data);
    }

    //redis存储
    private function redisCache($key, $value, $expire_time = 300)
    {
        Redis::setex($key, $expire_time, $value);
        return true;
    }
    //redis存储获取
    private function redisCacheGet($key)
    {
        return Redis::get($key);
    }
    //redis 存储删除
    private function redisCacheDel($key)
    {
        return Redis::del($key);
    }

    /**
     * cms 调用; 清除缓存
     * @param Request $request
     * $type 1 清除用户表; 2 清除用户钱包
     */
    /*
    public function clear_cache(Request $request){
        $this->service->set_cross();
        $key = (int) $request->post('key',0);
        $type = (int) $request->post('type',0);
        if(!$key || !$type){
            Response::returnResult(Hint::PARAM_ERROR);
        }

        if(1 === $type) $this->service->clear_cache($key, $type);
        if(2 === $type) $this->finance_services->clear_cache($key, $type);
        Response::returnResult(Hint::SUCCESS);
    }
    */


    /**
     * 设置靓号
     * @param $userId
     * @param $liang 0.非靓号、1.靓号
     */
    public function setLiang(Request $request)
    {
        $userId = $request->post('user_id');
        $liang = $request->post('liang');
        if (!isset($userId) || !isset($liang)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $this->service->setLiang($userId, $liang);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 设置超级管理
     * @param $userId
     * @param $super 0.非超管、1.超管
     */
    public function setSuper(Request $request)
    {
        $userId = $request->post('user_id');
        $super = $request->post('super');
        if (!isset($userId) || !isset($super)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $this->service->setSuper($userId, $super);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 设置官方
     * @param $userId
     * @param $official 0.非官方、1.官方
     */
    public function setOfficial(Request $request)
    {
        $userId = $request->post('user_id');
        $official = $request->post('official');
        if (!isset($userId) || !isset($official)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $this->service->setOfficial($userId, $official);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 设置接待(巡房)
     * @param $userId
     * @param $waiter 0.非接待、1.接待
     */
    public function setWaiter(Request $request)
    {
        $userId = $request->post('user_id');
        $waiter = $request->post('waiter');
        if (!isset($userId) || !isset($waiter)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $this->service->setWaiter($userId, $waiter);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 设置加V
     * @param $userId
     * @param $v 0.取消加V、1.设置加V
     * @param $vDesc 加V描述
     */
    public function setV(Request $request)
    {
        $userId = $request->post('user_id');
        $v = $request->post('v');
        $vDesc = $request->post('v_desc');
        $startTime = $request->post('start_time', 0);
        $endTime = $request->post('end_time', 0);
        if (!isset($userId) || !isset($v)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $this->service->setV($userId, $v, $vDesc, $startTime, $endTime);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 设置UID
     * @param $userId
     * @param $uid
     */
    public function setUid(Request $request)
    {
        $userId = $request->post('user_id');
        $uid = $request->post('uid');
        if (!isset($userId) || !isset($uid)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $data = $this->service->setUid($userId, $uid);
        if ($data == Hint::ERROR) {
            Response::returnResult(Hint::ERROR);
        }
        if ($data == Hint::USER_UID_NOT_LIANG) {
            Response::returnResult(Hint::USER_UID_NOT_LIANG);
        }
        if ($data == Hint::USER_UID_IS_EXIST) {
            Response::returnResult(Hint::USER_UID_IS_EXIST);
        }
        if ($data == Hint::USER_IS_NOT_EXIST) {
            Response::returnResult(Hint::USER_IS_NOT_EXIST);
        }
        Response::returnResult(Hint::SUCCESS);
    }


    public function loopAccountCancel()
    {
        $userIdArr = $this->service->loopAccountCancel();
        $trends = new TrendsServices();
        $trends->cleanUserTrends($userIdArr);
        //删除好友数据
        $friends = new FriendsServices();
        $friends->removeFriendFollowByUids($userIdArr);
    }


    /**
     * 认证
     * @param Request $request
     */
    public function cmsSetCertify(Request $request)
    {
        $user_id = $request->input('user_id', 0);
        $active_certify = $request->input('active_certify', 1);

        $res = $this->service->cms_set_certify($user_id, $active_certify);
        //Log::debug($res);
        if ($res) {
            Response::returnResult(Hint::SUCCESS);
        }
        Response::returnResult(Hint::ERROR);
    }



    /**
     * 设置封号用户
     * @param Request $request
     */
    public function getForbidUsers(Request $request)
    {
        $data = $this->service->getForbidUsers();
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 关键字搜索 用户/房间
     * */
    public function keywordsSearch()
    {
        do {
            if (!$this->checkRequest(false)) {

                break;
            }

            $this->callCommon($this->service, 'keywordsSearch', $this->requestData);



        } while (false);

        if (is_string($this->responseData))
            $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    ################# 后台调用 ##########################################

    /**
     * 用户封号创建
     * */
    public function blockCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'blockCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 封禁设备
     * @param Request $request
     */
    public function set_forbid_device()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'set_forbid_device', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 获取设备封禁状态
     * @param Request $request
     */
    public function get_forbid_device()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'get_forbid_device', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 设置IP封禁
     * @param Request $request
     */
    public function set_forbid_ip()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $user_id = $this->requestData['user_id'];
            try {
                $ips = UserLoginLog::where('user_id', $user_id)->select(['ip'])->get()->toArray();
                // for ($i = 0; $i < count($ips); $i++) {
                //     $ips[$i]['ip'] = implode('.', array_slice(explode('.', $ips[$i]['ip']), 0, 3));
                // }
                $ips = array_unique(array_column($ips, 'ip'));
                Redis::SADD($this->forbid_ip, $ips);
                Response::returnResult(Hint::SUCCESS);
            } catch (\Exception $e) {
                Response::returnResult(Hint::ERROR, [], $e->getMessage());
            }
        } while (false);
    }


    public function forbid_ip_list()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $data = $this->requestData['data'];
            try {
                for ($i = 0; $i < count($data); $i++) {
                    $ip = $data[$i]['ip'];
                    // $ipSegments = explode('.', $ip);
                    // $ipPrefix = implode('.', array_slice($ipSegments, 0, 3));
                    $forbidIps = Redis::SISMEMBER($this->forbid_ip, $ip);
                    if ($forbidIps) {
                        $data[$i]['forbid_status'] = 1;
                    } else {
                        $data[$i]['forbid_status'] = 0;
                    }
                }
                Response::returnResult(Hint::SUCCESS, $data);
            } catch (\Exception $e) {
                Response::returnResult(Hint::ERROR, [], $e->getMessage());
            }
        } while (false);
    }


    public function deny_ip_list()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            try {
                $items = [];
                foreach (Redis::SMEMBERS($this->forbid_ip) as $ip) {
                    $items[] = $ip;
                }
                $list = UserLoginLog::with(['user'])->whereIn('ip', $items)->get();

                Response::returnResult(Hint::SUCCESS, ['list' => $list]);
            } catch (\Exception $e) {
                Response::returnResult(Hint::ERROR, [], $e->getMessage());
            }
        } while (false);
    }

    public function remove_ip_forbid()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $ip = $this->requestData['ip'];
            try {
                Redis::SREM($this->forbid_ip, $ip);
                Response::returnResult(Hint::SUCCESS);
            } catch (\Exception $e) {
                Response::returnResult(Hint::ERROR, [], $e->getMessage());
            }
        } while (false);
    }

    /**
     * 设置IP解封
     * @param Request $request
     */
    public function set_unforbid_ip()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $user_id = $this->requestData['user_id'];
            try {
                $ips = UserLoginLog::where('user_id', $user_id)->select(['ip'])->get()->toArray();
                // for ($i = 0; $i < count($ips); $i++) {
                //     $ips[$i]['ip'] = implode('.', array_slice(explode('.', $ips[$i]['ip']), 0, 3));
                // }
                $ips = array_unique(array_column($ips, 'ip'));
                Redis::SREM($this->forbid_ip, $ips);
                Response::returnResult(Hint::SUCCESS);
            } catch (\Exception $e) {
                Response::returnResult(Hint::ERROR, [], $e->getMessage());
            }
        } while (false);
    }

    public function resetDevice()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'resetDevice', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 获取设备封禁状态
     * @param Request $request
     */
    public function get_user_forbid_status()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'get_user_forbid_status', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 用户封号更新
     * */
    public function blockUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'blockUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 用户封号删除
     * */
    public function blockRemove()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'blockRemove', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 用户信息编辑
     * */
    public function editUserInfo()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'editUserInfo', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 设置账号异常
     * @param $userId
     * @param $v 0.取消加V、1.设置加V
     * @param $vDesc 加V描述
     */
    public function setAbnormal(Request $request)
    {
        $userId = $request->post('user_id');
        $is_abnormal = $request->post('is_abnormal');
        if (!isset($userId) || !isset($is_abnormal)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $this->service->setAbnormal($userId, $is_abnormal);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 用户账号注销
     * */
    public function accountCancel()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            $this->callCommon($this->service, 'accountCancel', $this->requestData);

        } while (false);


        if (is_string($this->responseData))
            $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 用户隐身道具失效
     * */
    public function propInvalid()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            $this->callCommon($this->service, 'propInvalid', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /*
     * 检测用户数据 检测数据包含
     * 文字-用户昵称
     * 文字-用户签名
     * 语音-我的声音
     * 图片-相册/头像
     *
     * */
    public function checkUserContent($request, $nickname, $sign, $voice, $images, $prepare_img)
    {
        $checkResult = $this->contentCheckServices->checkUserContent($request->input());
        return $checkResult;
        //初始化数据 不提交 进入审核机制
//        $nickname = (isset($checkResult['nickname']) && $nickname) ? $checkResult['nickname'] : "";
//        $sign = (isset($checkResult['sign']) && $sign) ? $checkResult['sign'] : "";
//        $voice = (isset($checkResult['voice']) && $voice) ? $checkResult['voice'] : "";
//        $images = (isset($checkResult['images']) && $images) ? $checkResult['images'] : "";
    }

    /**
     * 获取用户邀请列表
     * */
    public function getUserInviteList()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            $this->callCommon($this->service, 'getUserInviteList', $this->requestData, false);

        } while (false);

        if (is_string($this->responseData))
            $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * wap 公众号登录信息
     * @param Request $request
     */
    public function get_wx_user_token(Request $request)
    {
        $source = $request->post('source');
        $platform = $request->post('platform');
        $code = $request->post('code');


        $ret = $this->service->getUserTokenService($source, $platform, $code);
        if (empty($ret)) {
            Response::returnResult(Hint::ERR_FAIL, []);
        }
        Response::returnResult(Hint::SUCCESS, $ret);
    }

    /**
     * 获取用户邀请信息
     * */
    public function getUserInviteInfo()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->service, 'getUserInviteInfo', $this->requestData, false);

        } while (false);

        if (is_string($this->responseData))
            $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    # ------------------------------------------------------------------------------------------

    /**
     * 根据用户ID获取用户信息
     * @param Request $request
     * */
    public function infoById(Request $request)
    {
        $this->responseData($this->service->infoById($request->input()));
    }

    /**
     * 根据token获取用户信息
     * @param Request $request
     * */
    public function infoByToken(Request $request)
    {
        $this->responseData($this->service->infoByToken($request->input()));
    }

    /**极光登录
     * @param Request $request
     */
    public function jgLogin(Request $request)
    {
        $loginToken = $request->input('loginToken') ?? '';
        $inviteCode = $request->input('invite_code');
        $deviceId = $request->input('deviceId') ?? '';
        $advertisingId = $request->input('advertisingId') ?? '';
        $cancel = $request->input('cancel') ?? null;

        $ua = $this->service->parse_app_UA();
        $versionNo = $ua['version_no'] ?? "";
        $osName = strtolower($ua["os_name"] ?? "");

        if (!$loginToken) {
            Response::returnResult(Hint::TOKEN_ERROR);
        }
        $phone = $this->service->jgLogin($loginToken);
        if (empty($phone)) {
            Response::returnResult(Hint::JG_TOKEN_CHECK_ERROR);
        }

        #region  检查IP是否封禁
        $ip = client_ip();
        // $ipSegments = explode('.', $ip);
        // $ipPrefix = implode('.', array_slice($ipSegments, 0, 3));
        // write_log('zq', 'forbid_ip', ['ip' => $ipPrefix]);
        $forbidIps = Redis::SISMEMBER($this->forbid_ip, $ip);
        $ips = Redis::SMEMBERS($this->forbid_ip);
        if ($forbidIps) {
            write_log('zq', 'forbid_ip', ['forbidIps' => $forbidIps, 
            //  'ipSegments' => $ipSegments, 'ipPrefix' => $ipPrefix,
            'ip' => $ip, 'ips' => $ips]);
            Response::returnResult(Hint::DEVICE_FORBID, [], 'IP已封禁');
        }
        #endregion

        //获取手机号注册状态
        $phoneStatus = $this->service->phoneStatus($phone);
        //进行账号注册 status = 1
        if ($phoneStatus == 1) {
            write_log('user-invite', 'jgLogin', ['invite_code' => $inviteCode, 'phone' => $phone]);
            $inviteUserIdNew = 0;

            $inviteUserData = $this->service->getUserInfoByCode($inviteCode);
            if (!empty($inviteUserData) && $inviteUserData['is_open_code'] == 1) {
                $inviteUserIdNew = $inviteUserData['user_id'];
            }


            $userId = $this->service->createUserNPwdService($phone, 0, $inviteUserIdNew);
            if ($userId) {
                $this->service->createWalletService($userId);

                //查询数据
                $data = $this->service->getResponseData($userId);
                $data['rong_token'] = $this->service->get_rong_token($data);
                event(new RoomRegisterEvent($data, 1));
                // 绑定推荐人
                $this->popularize_service->check_recommend_code($userId);

                // 写注册日志、广告归因上报
                $this->service->user_register_log($userId);

                $this->service->update_channel_guid($userId);

                // TODO 发布消息通知
                $content = [
                    'user_id' => $userId,
                    'target_id' => 0,
                    'time' => time(),
                    'deviceid' => $deviceId,
                    'timestamp' => msectime(),
                    'ip' => client_ip(),
                    'is_phone_exiist' => 0,
                    'country_code' => '0086',
                    'ua' => $this->service->parse_app_UA()
                ];
                $this->systemServices->deviceRiskQueue($content);
                Response::returnResult(Hint::SUCCESS, $data);
            }
            Response::returnResult(Hint::ERROR);
        }

        //进行账号登录 //type=1：手机号密码 2：手机号验证码 3：第三方
        $ret = $this->service->local_login(3, ['phone' => $phone], $user_id, $cancel);
        //获取设备是否封禁状态
        if ($ret == Hint::DEVICE_FORBID) {
            Response::returnResult(Hint::DEVICE_FORBID, [], '设备已封禁');
        }
        if ($ret == Hint::USER_IS_NOT_EXIST) {
            Response::returnResult(Hint::USER_IS_NOT_EXIST);
        }
        if ($ret == Hint::USER_FORBID) {
            $forbidTime = $this->service->getForbidTime($user_id);
            $forbidInfo = $this->service->getBlockInfo($user_id);
            $forbidDurationTime = 0;
            if (!empty($forbidInfo)) {
                $forbidDurationTime = $forbidInfo['block_duration_time'];
            }
            Response::returnResult(Hint::USER_FORBID, ["forbid_time" => $forbidTime, "forbid_duration_time" => $forbidDurationTime]);
        }
        if ($ret == Hint::USER_ACCOUNT_IS_CANCEL) {
            Response::returnResult(Hint::USER_ACCOUNT_IS_CANCEL);
        }
        if ($ret == Hint::ERROR) {
            Response::returnResult(Hint::ERROR);
        }
        if ($ret == Hint::PASSWORD_ERROR) {
            Response::returnResult(Hint::PASSWORD_ERROR);
        }

        $this->service->user_login_log($user_id, $deviceId, $advertisingId);
        $this->service->update_channel_guid($user_id);
        Response::returnResult(Hint::SUCCESS, $ret);
    }


    /**数美二次校验验证码
     * @param Request $request
     */
    public function shumeiVerifyCode(Request $request)
    {
        $rid = $request->post('rid');
        $deviceId = $request->post('deviceId', '');
        $phone = $request->post('phone');
        if (empty($rid)) {
            Response::returnResult(Hint::PARAM_ERROR, [], '划块标识符不能为空');
            return;
        }
        /*if(empty($deviceId)){
            Response::returnResult(Hint::PARAM_ERROR, [], '设备id不能为空');
            return;
        }*/
        if (empty($phone)) {
            Response::returnResult(Hint::PARAM_ERROR, [], '手机号不能为空');
            return;
        }
        $code = $this->service->shumeiVerfyCode($rid, $request->ip(), $phone, $deviceId);
        if ($code == 0) {
            $redisDeviceKey = $this->smsPrefix . $phone . '_' . $deviceId;
            $this->service->redisCacheDevice($redisDeviceKey, 1);
        }
        Response::returnResult($code, []);
    }

    /**
     * 设置礼物开关
     */
    public function setGiftSwitch()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->service, 'setGiftSwitch', $this->requestData);

        } while (false);

        if (is_string($this->responseData))
            $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 获取公会马甲相关信息
     */
    public function getUnionVestInfo()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->service, 'getUnionVestInfo', $this->requestData);

        } while (false);


        if (is_string($this->responseData))
            $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 添加用户每日最大充值金额
     */
    public function curdRechargeLimit()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $this->callCommon($this->service, 'curdRechargeLimit', $this->requestData);

        } while (false);

        $this->responseData();
    }

    public function delRechargeLimit()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $this->callCommon($this->service, 'delRechargeLimit', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 获取赠送/充库存权限
     */
    public function getFinanceProxyStatus()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->service, 'getFinanceProxyStatus', $this->requestData);

        } while (false);

        $this->responseData();
    }
    # ------------------------------------------------------------------------------------------

    //获取默认头像和昵称
    public function getDefaultInfo()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->service, 'getDefaultInfo', $this->requestData);

        } while (false);

        if (is_string($this->responseData))
            $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    //获取所有备注
    public function getRemark()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->service, 'getRemark', $this->requestData);

        } while (false);

        $this->responseData();
    }


    /**
     * 后台操作-换绑手机号
     */
    public function changeBindPhone()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $this->callCommon($this->service, 'changeBindPhone', $this->requestData);

        } while (false);

        $this->responseData();
    }

    //定时注销账号
    public function cancelAccount()
    {
        $userIdArr = $this->service->loopAccountCancel();
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 标签列表
     */
    public function getUserTagsList()
    {
        Response::returnResult(Hint::SUCCESS, $this->service->getUserTagsList());
    }

    /**
     * 标签列表
     */
    public function getUserTagsWithCat()
    {
        $list = $this->service->getUserTagsWithCat();
        Response::returnResult(Hint::SUCCESS, ['list' => $list]);
    }



    /**
     * 设置用户标签
     *
     * @param int $type 0 关于我; 1 关于他
     */
    public function setUserTags(Request $request)
    {
        $this->service->checkToken();

        $tags = $request->post('tags', '');
        $type = (int) $request->post('type', 0);
        if (!in_array($type, [0, 1])) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $this->service->setUserTags($tags, $type);
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 创建用户标签
     */
    public function createUserTag(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'bail|required|string'
        ], [
            'name.required' => '标签名不可为空',
            'name.string' => '便签名必须是字符类型'
        ]);
        if ($validator->fails()) {
            return Response::returnResult(Hint::PARAM_ERROR, [], $validator->errors()->first());
        }
        $this->service->createUserTag($request->only(['name', 'sort', 'status', 'type', 'cat']));
        Response::returnResult(Hint::SUCCESS);
    }

    public function updateUserTag(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'bail|required|exists:user_tags,tag_id',
            'name' => 'bail|required|string'
        ], [
            'id.required' => '个性标签不可为空',
            'id.exists' => '个性标签不存在',
            'name.required' => '标签名不可为空',
            'name.string' => '便签名必须是字符类型'
        ]);
        if ($validator->fails()) {
            Response::returnResult(Hint::PARAM_ERROR, [], $validator->errors()->first());
        }
        $this->service->updateUserTag($request->post('id'), $request->only(['name', 'status', 'sort', 'type', 'cat']));
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * [createUserTagsCat 添加个性标签分类]
     */
    public function createUserTagsCat(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'bail|required|string',
            'sort' => 'bail|required|max:100',
        ], [
            'name.required' => '个性标签分类不可为空',
            'name.string' => '个性标签分类名必须是字符类型'
        ]);
        if ($validator->fails()) {
            Response::returnResult(Hint::PARAM_ERROR, [], $validator->errors()->first());
        }
        $res = $this->service->createUserTagsCat($request->only(['name', 'sort', 'status', 'type']));
        if (!$res) {
            Response::returnResult(Hint::ERROR);
        }
        Response::returnResult(Hint::SUCCESS);
    }
    /**
     * [createUserTagsCat 更新个性标签分类]
     */
    public function updateUserTagsCat(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'bail|required|exists:user_tags_cat,id',
            'name' => 'bail|required|string',
            'sort' => 'bail|required|max:100',
        ], [
            'id.required' => '个性标签分类ID不可为空',
            'id.exists' => '个性标签分类ID不存在',
            'name.required' => '个性标签分类不可为空',
            'name.string' => '个性标签分类必须是字符类型'
        ]);
        if ($validator->fails()) {
            Response::returnResult(Hint::PARAM_ERROR, $validator->errors()->first());
        }
        $res = $this->service->updateUserTagsCat($request->post('id'), $request->only(['name', 'sort', 'status', 'type']));
        if (!$res) {
            Response::returnResult(Hint::ERROR);
        }
        Response::returnResult(Hint::SUCCESS);
    }
    /**
     * [delUserTagsCat 删除个性标签分类]
     */
    public function delUserTagsCat(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'bail|required|exists:user_tags_cat,id'
        ], [
            'id.required' => '个性标签分类ID不可为空',
            'id.exists' => '个性标签分类ID不存在',
        ]);
        if ($validator->fails()) {
            Response::returnResult(Hint::PARAM_ERROR, [], $validator->errors()->first());
        }
        $res = $this->service->delUserTagsCat($request->post('id'));
        if (!$res) {
            Response::returnResult(Hint::ERROR);
        }
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 私聊信息用户资料卡
     */
    public function getPrivateChatUserInfo(Request $request)
    {
        $this->service->checkToken();
        $validator = Validator::make($request->all(), [
            'user_id' => 'bail|required|exists:user,user_id'
        ], [
            'user_id.required' => '用户id不可为空',
            'user_id.exists' => '用户不存在'
        ]);
        if ($validator->fails()) {
            Response::returnResult(Hint::PARAM_ERROR, [], $validator->errors()->first());
        }

        $userId = $request->get('user_id');
        $list = $this->service->privateChatUserInfo($userId);

        // 最近动态
        $list['trends'] = (new TrendsServices)->latelyTrends($userId);

        Response::returnResult(Hint::SUCCESS, $list);
    }

    /**
     * 私聊时候获取对方背景图片
     */
    public function getPrivateChatBackImg(Request $request)
    {
        $this->service->checkToken();
        //私聊人id
        $chatwithUser = $request->get('chatUserId', 0);
        if (empty($chatwithUser)) {
            Response::returnResult(Hint::PARAM_ERROR, '缺少对方id', []);
        }
        //获取对方装扮
        $chatUserAttire = $this->mallService->getOtherUserAttire($chatwithUser);
        $returnData = [];
        //若不是聊天背景的type=10则不返回
        if (!empty($chatUserAttire)) {
            foreach ($chatUserAttire as $k => $v) {
                if ($v['goods_type'] == 10) {
                    $returnData = $v;
                    break;
                }
            }
        }
        Response::returnResult(Hint::SUCCESS, $returnData);
    }

    /**
     * 用户自动注销回调
     *
     * @param Request $request
     */
    public function deleteUserCallback(Request $request)
    {
        $userId = $request->input('user_id', 0);
        (new UserAccountCancel())->cancelUser($userId);
        Response::returnResult(Hint::SUCCESS);
    }


    public function getTestUser()
    {
        $res = $this->service->getTestUser();
        if ($res) {
            Response::returnResult(Hint::SUCCESS, $res);
        }
        Response::returnResult(Hint::ERROR);
    }

    public function addTestUser(Request $request)
    {
        $user_id = $request->input('user_id');
        if (!$user_id) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $res = $this->service->addTestUser($user_id);
        if ($res) {
            Response::returnResult(Hint::SUCCESS);
        }
        Response::returnResult(Hint::ERROR);
    }

    public function delTestUser(Request $request)
    {
        $user_id = $request->input('user_id');
        if (!$user_id) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $res = $this->service->delTestUser($user_id);
        if ($res) {
            Response::returnResult(Hint::SUCCESS);
        }
        Response::returnResult(Hint::ERROR);
    }
    public function getCookieToken()
    {
        $userService = new UserServices();
        $user_id = $userService->get_current_user_id();
        $seltArr = ['ll-activity', 'llai', 'lailai'];
        $rand = rand(0, 2);
        $rand1 = rand(0, 2);
        $token = md5($seltArr[$rand] . $user_id . md5($seltArr[$rand1])) . '-' . $user_id . '-' . $rand . $rand1;
        Response::returnResult(Hint::SUCCESS, ['token' => $token]);
    }

    public function fullscreenHideCheck()
    {
        $userId = $this->service->get_current_user_id();
        $hide = (new UserFilterServices())->hideFullScreenAndAdEntrance($userId);// 获取用户城市
        Response::returnResult(Hint::SUCCESS, ['hide' => $hide]);
    }

    public function rongCallback(Request $request)
    {
        write_log('rongCallback', 'rongCallbackRequest', $request->input());
        $data = ['pass' => 0];
        $fromUserId = $request->input('fromUserId');
        if (!$fromUserId) {
            return json_encode($data);
        }
        $wealth_balance = $this->service->getUserWealthBalance($fromUserId);
        if ($wealth_balance > 60) {
            $data = ['pass' => 1];
        }
        write_log('rongCallback', 'rongCallbackData', $data);
        return json_encode($data);
    }

    /**
     * @param MsgServices $service_msg
     */
    public function addShareAnchor(Request $request)
    {
        $user_id = $request->input('user_id');
        if ($user_id <= 0) {
            $userService = new UserServices();
            $user_id = $userService->get_current_user_id();
            $request['user_id'] = $user_id;
        }
        $servise = new UserAnchorServices();
        $res = $servise->addLog($request->all());
        return json_encode($res);

    }

    /**
     * 用户简易注销
     * 简易注销是指仅删除用户手机号以及认证信息，不会删除软件中发布的任何内容。
     * */
    public function simpleAccountCancel(Request $request)
    {

        $userId = $request->input('user_id');
        if (!$userId) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $result = $this->service->simpleAccountCancel($userId);

        if ($result === Hint::USER_IS_NOT_EXIST) {
            Response::returnResult(Hint::USER_IS_NOT_EXIST);
        }

        Response::returnResult(Hint::SUCCESS, $result);
    }
    /**
     * 用户未消费钻石，金币以及背包礼物数量
     */
    public function getUserGift()
    {
        $this->service->getUserGift();
    }

    /***
     * 获取用户首冲礼包
     * @param Request $request
     * @return void
     */
    public function getUserFirstRechargeList(Request $request)
    {

        $userId = $request->input('user_id');
        if (!$userId) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $result = $this->service->getUserFirstRechargeList($userId);

        if ($result["firstRechargeData"] === Hint::USER_NOT_EXIST) {
            Response::returnResult(Hint::USER_NOT_EXIST);
        }

        Response::returnResult(Hint::SUCCESS, $result);
    }
}
